import 'dart:async';
import 'package:flutter_mvp/contact/data/contact_data.dart';
import 'package:flutter/services.dart';
import 'dart:convert';

//
// Created by StephenChen on 2018/4/3.
//
// 数据模型操作，处理网络请求，缓存等
//

// 测试数据
class MockContactRepository implements ContactRepository {
  @override
  Future<List<Contact>> fetch() {
    return new Future.value(kContacts);
  }
}

const kContacts = const <Contact>[
  const Contact(fullName: "Li bai", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Cheng yaojin", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Mi yue", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "A ke", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Lu ban", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Da qiao", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Hou yi", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Liu bei", email: " aliyunzixun@xxx.com"),
  const Contact(fullName: "Wang zhaojun", email: " aliyunzixun@xxx.com"),
];

// 网络数据
class HttpContactRepository implements ContactRepository {
  final String kContactsUrl = "http://o6p4e1uhv.bkt.clouddn.com/contacts.json";

  @override
  Future<List<Contact>> fetch() async {
    var httpClient = createHttpClient();
    var response = await httpClient.get(kContactsUrl);
    List<Map> contacts = jsonDecode(response.body)['contacts'];
    return contacts.map((contact) {
      return new Contact(
          fullName: contact['fullname'], email: contact['email']);
    }).toList();
  }
}

// 数据切换
enum RepositoryType { mock, http }

class Injector {
  ContactRepository getContactRepository(RepositoryType type) {
    switch (type) {
      case RepositoryType.mock:
        return new MockContactRepository();
      default:
        return new HttpContactRepository();
    }
  }
}
